package com.aloha.springframework.aop.framework.autoproxy;

import com.aloha.springframework.aop.Advisor;
import com.aloha.springframework.aop.Pointcut;
import com.aloha.springframework.aop.PointcutAdvisor;
import com.aloha.springframework.aop.TargetSource;
import com.aloha.springframework.aop.framework.ProxyFactory;
import com.aloha.springframework.beans.BeansException;
import com.aloha.springframework.beans.factory.BeanFactory;
import com.aloha.springframework.beans.factory.BeanFactoryAware;
import com.aloha.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import com.aloha.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.aopalliance.aop.Advice;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author DaiZhiHeng
 * @date 2023/8/1 21:58
 */
public abstract class AbstractAdvisorAutoProxyCreator implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {

    protected DefaultListableBeanFactory beanFactory;

    protected final Map<String, Object> earlyProxyReferences = new ConcurrentHashMap<>(16);

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (bean != null) {
            // 这种情况表明没有创建过代理，也就是没有发生关于代理对象的循环依赖
            if (earlyProxyReferences.remove(beanName) != bean) {
                return wrapIfNecessary(bean, beanName);
            }
        }
        return bean;
    }

    @Override
    public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
        earlyProxyReferences.put(beanName, bean);
        return wrapIfNecessary(bean, beanName);
    }

    protected Object wrapIfNecessary(Object bean, String beanName) {
        // 不能被创建代理的类
        if (isInfrastructureClass(bean.getClass())) return bean;

        // 返回类型匹配的切面
        List<Advisor> advisors = findEligibleAdvisors(bean.getClass(), beanName);

        // 如果该类对象没有类型匹配的切面，说明不需要代理，返回原对象即可
        if (advisors.isEmpty()) return bean;
        TargetSource targetSource = new TargetSource(bean); // 封装代理对象
        return createProxy(targetSource, advisors);
    }

    // 创建代理
    protected Object createProxy(TargetSource targetSource, List<Advisor> advisors) {
        ProxyFactory proxyFactory = new ProxyFactory(); // 创建代理对象工厂
        proxyFactory.setTargetSource(targetSource);
        proxyFactory.addAdvisor(advisors);
        // 返回代理对象
        return proxyFactory.getProxy();
    }

    // 对于和代理相关的类，不能为它们创建代理
    protected boolean isInfrastructureClass(Class<?> beanClass) {
        return Advice.class.isAssignableFrom(beanClass) || Pointcut.class.isAssignableFrom(beanClass) || Advisor.class.isAssignableFrom(beanClass);
    }

    /**
     * 获取所有和 beanClass 匹配的 Advisor
     */
    protected abstract List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) throws BeansException;
}
